<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" @click="isMaintain" :disabled="roles == common">维修完成</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出</el-button>
        <el-input placeholder="单号" clearable style="width: 240px;margin-left: 10px;" @keyup.enter.native=""
          v-model="queryParams.maintainCode" size="mini" /> &nbsp;&nbsp;
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList()">查询</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="maintainList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="maintainId" width="50px">
        <template slot-scope="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="单据状态" align="center" prop="receiptsStatus" width="80px">
        <template slot-scope="scope">
          <button class="but1" v-if="scope.row.receiptsStatus == 3">待审核</button>
          <button class="but2" v-if="scope.row.receiptsStatus == 2">已拒绝</button>
          <button class="but3" v-if="scope.row.receiptsStatus == 1">已审核</button>
          <button class="but4" v-if="scope.row.receiptsStatus == 4">已撤销</button>
        </template>
      </el-table-column>
      <el-table-column label="维修单号" align="center" prop="maintainCode" width="190px" />
      <el-table-column label="资产编码" align="center" prop="assetCode" width="130">
        <template slot-scope="scope">
          {{scope.row.asset.assetCode}}
        </template>
      </el-table-column>
      <el-table-column label="资产名称" align="center" prop="warrantyDate">
        <template slot-scope="scope">
          {{scope.row.asset.assetName}}
        </template>
      </el-table-column>
      <el-table-column label="报修日期" align="center" prop="warrantyDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.warrantyDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="报修原因" align="center" prop="cause" />
      <el-table-column label="是否维修" align="center" prop="isMaintain">
        <template slot-scope="scope">
          <span v-if="scope.row.isMaintain == 1">未维修</span>
          <span v-if="scope.row.isMaintain == 2">已维修</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="creatorName" />
      <el-table-column label="制单时间" align="center" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button size="mini" type="text" :disabled="scope.row.receiptsStatus != 3  || roles == 'common'"
            @click="opneAudit(scope.row)">审核</el-button>
          <el-button size="mini" type="text" @click="hadReturn(scope.row)"
            :disabled="scope.row.receiptsStatus != 1">撤回</el-button>
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)"><span
              style="font-size: 12px;">删除</span></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改用户配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="750px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="选择资产" style="margin-left: 30px;" prop="assetName">
              <el-input placeholder="请输入" show-word-limit v-model="eamAsset.assetCode" />
              <img class="img1" @click="open2Asset" src="../../../assets/image/搜索.png" width="27px"
                style="position: absolute;left: 180px;top:3px;cursor: pointer;" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="资产名称" prop="asseSpec" style="margin-left: 30px;">
              <el-input maxlength="30" style="width: 220px;" :disabled="true" v-model="eamAsset.assetName" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="资产类型" style="margin-left: 30px;" prop="model">
              <el-input maxlength="30" :disabled="true" v-model="eamAsset.typeName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="存放位置" prop="price" style="margin-left: 30px;">
              <el-input style="width: 220px;" :disabled="true" v-model="eamAsset.locationName" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="11">
            <el-form-item label="资产状态" style="margin-left: 30px;" prop="assetUnit">
              <el-input :disabled="true" v-model="eamAsset.statusName" />
            </el-form-item>
          </el-col>
          <el-col :span="11">
            <el-form-item label="资产金额" prop="assetUnit" style="margin-left: 30px;">
              <el-input style="width: 220px;" :disabled="true" v-model="eamAsset.price" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="报修日期" prop="warrantyDate" style="margin-left: 30px;">
              <el-date-picker type="date" placeholder="选择日期" value-format="yyyy-MM-dd" v-model="form.warrantyDate">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="11">
            <el-form-item label="报修原因" prop="cause" style="margin-left: 30px;">
              <el-input placeholder="请输入" style="width: 520px;" v-model="form.cause" />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-form-item label="资产图片:" style="margin-left: 35px;">
              <span>图片支持jpg.png.gif格式，单个图片大小最大为20M。最多上传10张图片</span>
              <el-upload action="#" ref="upload" list-type="picture-card" :auth-upload="false"
                :on-preview="handlePictureCardPreview" :on-remove="handleRemove" :http-request="uploadAvatar"
                :before-upload="beforeAvatarUpload" :file-list="fileList">
                <i class="el-icon-plus"></i>
              </el-upload>

              <el-dialog :visible.sync="dialogVisible">
                <img width="100%" :src="dialogImageUrl" alt="">
              </el-dialog>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm()">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!--选择资产-->
    <el-dialog :title="title2" :visible.sync="open2" width="1000px" append-to-body>
      <el-row>
        <el-col :span="24">
          <el-input placeholder="资产名称" maxlength="30" style="width: 200px;" v-model="asset.assetName" />&nbsp;
          <el-select placeholder="全部资产类型" v-model="asset.typeId" clearable>
            <el-option v-for="item in typeList" :key="item.typeId" :label="item.typeName"
              :value="item.typeId"></el-option>
          </el-select>&nbsp;
          <el-select placeholder="全部存放位置" v-model="asset.locationId" clearable>
            <el-option v-for="item in locationList" :key="item.locationId" :label="item.locationName"
              :value="item.locationId"></el-option>
          </el-select>&nbsp;
          <el-button type="primary" icon="el-icon-search" size="mini" @click="open2Asset"
            style="height: 34px;">查询</el-button>
          <el-table :data="assetList" border style="padding-top: 10px;" @selection-change="assetSelectionChange"
            v-loading="loading1">
            <el-table-column type="selection" width="50" align="center" />
            <el-table-column label="资产名称" align="center" prop="assetName" />
            <el-table-column label="资产编码" align="center" prop="assetCode" :min-width="150" />
            <el-table-column label="资产类型" align="center" prop="typeName" />
            <el-table-column label="规格" align="center" prop="asseSpec" />
            <el-table-column label="型号" align="center" prop="model" />
            <el-table-column label="资产金额(元)" align="center" prop="price" />
            <el-table-column label="报废日期" align="center" prop="scrapTime" />
          </el-table>
        </el-col>
      </el-row>
      <!-- 分页 -->
      <pagination class="fy" v-show="total2>0" :total="total2" :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize" @pagination="getList()" />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submit" :disabled="isSave">确 定</el-button>
        <el-button @click="cancel2">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 审核 -->
    <el-dialog :title="title4" :visible.sync="open4" width="620px" append-to-bod>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <div>
          <el-form-item label="审核原因:" prop="nickName" style="height: 100px;">
            <el-input v-model="auditReason" type="textarea" maxlength="300" show-word-limit :rows="4"
              style="min-height: 100px;"> </el-input>
          </el-form-item>
        </div>
        <div style="text-align: right;margin-top: 10px;">
          <el-button @click="cancel4">取 消</el-button>
          <el-button type="warning" @click="audit(2)">不通过</el-button>
          <el-button type="primary" @click="audit(1)">通过</el-button>
        </div>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
  import {
    listMaintain,
    getMaintain,
    delMaintain,
    addMaintain,
    updateMaintain,
    updateMaintainsStatus,
    assetMaintainStatus
  } from "@/api/eam-xl/maintain";
  import {
    getTypeList,
    getEamList
  } from "@/api/eam-xl/allot";
  import {
    getInfo
  } from "@/api/login";
  import {
    updateEam,
    uploadImage,
  } from "@/api/eam-xl/index";

  export default {
    name: "Maintain",
    data() {
      return {
        //文件上传用
        dialogImageUrl: '',
        dialogVisible: false,
        fileList: [],
        // 遮罩层
        loading: true,
        loading1: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        total2: 0,
        // 资产维修表格数据
        maintainList: [],
        // 弹出层标题
        title: "",
        title2: "选择资产",
        title3: "单据流水",
        title4: "系统提示",
        // 是否显示弹出层
        open: false,
        open2: false,
        open3: false,
        open4: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          assetId: null,
          maintainCode: null,
          isdel: 1
        },
        radio: undefined,
        // 表单参数
        form: {
          auditReason: undefined,
          cause: undefined,
          warrantyDate: undefined
        },
        // 表单校验
        rules: {
          warrantyDate: [{
            required: true,
            message: "请选择报修日期",
            trigger: "change"
          }],
          cause: [{
            required: true,
            message: "请输入报修原因",
            trigger: "blur"
          }],
        },
        locationList: [], //存放位置集合
        typeList: [],
        assetList: [],
        asset: { //资产
          assetName: undefined,
          typeId: undefined,
          locationId: undefined
        },
        fileImages: [],
        isSave: true,
        eamAsset: {},
        user: {},
        roles: undefined,
        files: [], //存放资产图片
        auditReason: undefined,
        chooseList: [],
      };
    },
    created() {
      this.getList();
      getTypeList().then((res) => {
        this.locationList = res.locationList;
        this.typeList = res.typeList;
      })
      getInfo().then((res) => {
        this.user = res.user;
        this.roles = res.roles;
      });
    },
    methods: {
      /** 查询资产维修列表 */
      getList() {
        this.loading = true;
        listMaintain(this.queryParams).then(response => {
          this.maintainList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.form = {};
        this.eamAsset = {};
        this.files = [];
        this.fileList = [];
        this.$refs["form"].resetFields();
        this.reset();
      },
      cancel2() { //选择资产取消按钮
        this.open2 = false;
        this.asset = {};
        this.eamAsset = {};
      },
      cancel4() {
        this.open4 = false;
        this.auditReason = "";
      },
      // 表单重置
      reset() {
        this.form = {
          maintainId: null,
          assetId: null,
          maintainCode: null,
          receiptsStatus: null,
          warrantyDate: null,
          cause: null,
          creator: null,
          createTime: null,
          locationId: null,
          auditperson: null,
          auditReason: null,
          auditTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.chooseList = selection;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加资产维修";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.form = row;
        this.eamAsset = row.asset
        this.title = "修改资产维修";
        this.open = true;
      },
      /** 提交按钮 */
      submitForm() {
        let _this = this;
        if (this.form.maintainCode == null) { //添加
          if (this.files.length == 0) {
            this.$message({
              message: '请添加资产图片',
              type: 'warning'
            });
            return;
          }
          if (this.eamAsset.assetCode == null) {
            this.$message.warning("请选择需要维修的资产");
            return;
          }
          const formData = new FormData();
          _this.files.forEach((file, index) => {
            formData.append("files", file);
          });
          formData.append("assetId", 0); //判断新增还是修改
          formData.append("type", "maintain"); //判断新增还是修改
          //新增
          this.eamAsset.useStatus = 103;
          _this.form.receiptsStatus = 3;
          _this.form.creator = _this.user.userId;
          _this.$refs["form"].validate((valid) => { //添加表单验证
            if (valid) {
              addMaintain(_this.form).then((res) => {
                //上传图片
                uploadImage(formData).then(res => {
                  _this.$modal.msgSuccess("添加成功");
                  _this.open = false;
                  _this.loading = true;
                  _this.getList();
                  _this.cancel();
                })
                updateEam(_this.eamAsset); //修改资产状态为维修
              });
            }
          })
        } else { //修改
          if (this.roles == "common") {
            if (this.user.userId != this.form.prepared) {
              this.$message.warning("您没有此权限")
              return;
            }
          }
          const formData = new FormData();
          //新增
          if (this.form.receiptsStatus == 4) {
            _this.form.receiptsStatus = 3;
          }
          _this.$refs["form"].validate((valid) => { //添加表单验证
            if (valid) {
              updateMaintain(_this.form).then((res) => {
                this.$message.success(res.msg);
                if (this.files.length != 0) { //是否修改图片
                  formData.append("assetId", this.form.assetId); //判断新增还是修改
                  formData.append("type", "maintain"); //判断新增还是修改
                  _this.files.forEach((file, index) => {
                    formData.append("files", file);
                  });
                  //上传图片
                  uploadImage(formData).then(res => {
                    _this.open = false;
                    _this.loading = true;
                    _this.getList();
                    _this.cancel();
                  })
                } else {
                  _this.open = false;
                  _this.loading = true;
                  _this.getList();
                  _this.cancel();
                }
              });
            }
          })


        }

      },
      /** 删除按钮操作 */
      handleDelete(row) {
        let _this = this;
        if (this.roles == "common") {
          if (this.user.userId != this.form.creator) {
            this.$message.warning("您没有此权限")
            return;
          }
        }
        this.$modal.confirm('是否确认删除资产维修编号为"' + row.maintainCode + '"的数据项？').then(function() {
          row.isdel = 0;
          updateMaintain(row).then(res => {
            this.getList();
            this.$modal.msgSuccess("操作成功");
          })
        }).then(() => {}).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('eam/maintain/export', {
          ...this.queryParams
        }, `maintain_${new Date().getTime()}.xlsx`)
      },
      // 文件上传
      beforeAvatarUpload(file) {
        //上传限制
        const isJPG = file.type === 'image/jpeg'
        const isPng = file.type === 'image/png'
        const isGif = file.type === 'image/gif'
        const isLt2M = file.size / 1024 / 1024 < 20

        if (!isJPG && !isPng && !isGif) {
          this.$message.error('上传图片只能是 JPG、png、Gif 格式!')
        }
        if (!isLt2M) {
          this.$message.error('上传图片大小不能超过 20MB!');
        }
        this.fileImages.push(file);
        if (this.fileImages.length > 10) {
          this.$message.warning("最多上传10张图片")
          return false;
        }
        return (isJPG || isPng) && isLt2M
      },

      handleRemove(file, fileList) { //文件删除
        // 找到元素的索引
        let index = this.files.indexOf(file.raw);
        // 如果找到了元素，就使用splice删除它
        if (index != -1) {
          this.files.splice(index, 1);
        }
        // this.files.splice(file,1);
      },
      handlePictureCardPreview(file) { // 显示大图
        this.dialogImageUrl = file.url;
        this.dialogVisible = true;
      },
      uploadAvatar(item) {
        //自定义上传的实现
        this.files.push(item.file);
      },
      emptyUpload() {
        //清空上传组件
        console.log("----upload.clearFiles");
        const mainImg = this.$refs.upload
        if (mainImg) {
          if (mainImg.length) {
            mainImg.forEach(item => {
              item.clearFiles()
            })
          } else {
            this.$refs.upload.clearFiles()
          }
        }
      },
      assetSelectionChange(selection) {
        if (selection.length == 1) {
          this.isSave = false; //取消禁用
          this.eamAsset = selection[0];
        } else { //禁用确定按钮
          this.isSave = true;
        }
      },
      open2Asset() { //选择资产弹框 ,搜索图标按钮
        this.open2 = true;
        this.loading1 = true;
        assetMaintainStatus(this.asset).then(res => {
          this.assetList = res.rows;
          this.loading1 = false;
        })
      },
      submit() {
        this.form.assetId = this.eamAsset.assetId;
        console.log(JSON.stringify(this.form))
        this.open2 = false;
      },
      hadReturn(row) { //撤回维修单
        //单据状态必须是待审核才可以撤回
        let _this = this;
        if (this.roles == "common") {
          if (this.user.userId != row.creator) {
            this.$message.warning("您没有此权限");
            return;
          }
        }
        this.$confirm('是否撤回' + row.maintainCode + "单号", '系统提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          //撤回
          row.receiptsStatus = 4;
          updateMaintain(row).then((res) => {
            this.$message.success(res.msg);
            this.getList();
          })

        })
      },
      audit(status) { //审核方法

        this.form.auditReason = this.auditReason;
        this.form.auditPerson = this.user.userId;
        this.form.receiptsStatus = status;
        this.form.auditDate = new Date().toLocaleString();
        this.open4 = false;
        updateMaintain(this.form).then(res => {
          this.$message.success(res.msg);
          this.cancel4();
          this.getList();
        })
      },
      opneAudit(row) { //打开审核界面dialog
        this.form = row;
        this.open4 = true;
      },
      isMaintain(status) {
        let _this = this;
        if (this.chooseList.length == 0) {
          this.$message.warning("请选择维修单")
        } else {
          let num = 0;
          this.chooseList.forEach((item, index) => {
            if (item.receiptsStatus != 1) {
              num = 1;
              return;
            }
          })
          if (num == 1) {
            _this.$message.warning("审核未通过不支持维修");
          } else {
            this.chooseList.forEach((item, index) => {
              item.isMaintain = 2;
            })
            updateMaintainsStatus(this.chooseList).then(res => {
              this.$message.success(res.msg)
              this.getList();
            })
          }

        }
      }
    }
  };
</script>

<style>
  /* 单据状态 */
  .but1 {
    color: sandybrown;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ffdcbc;
    border: 1px solid sandybrown;
  }

  .but2 {
    color: #aa3800;
    border-radius: 30px;
    font-size: 11px;
    background-color: #ff8d6a;
    border: 1px solid #ff8d6a;
  }

  .but3 {
    color: #4ab0f9;
    border-radius: 30px;
    font-size: 11px;
    background-color: #e6eff4;
    border: 1px solid #4ab0f9;
  }

  .but4 {
    color: #550000;
    border-radius: 30px;
    font-size: 11px;
    background-color: #d1d9dd;
    border: 1px solid #550000;
  }
</style>
